package com.campus.food.util;

import com.campus.food.security.UserPrincipal;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * 安全工具类
 * 用于获取当前登录用户信息
 * 
 * @author Claude3.7 Sonnet
 * @since 2025-05-29
 */
public class SecurityUtil {
    
    /**
     * 获取当前登录用户信息
     * 
     * @return 用户主体信息
     */
    public static UserPrincipal getCurrentUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.getPrincipal() instanceof UserPrincipal) {
            return (UserPrincipal) authentication.getPrincipal();
        }
        return null;
    }
    
    /**
     * 获取当前登录用户ID
     * 
     * @return 用户ID
     */
    public static Long getCurrentUserId() {
        UserPrincipal user = getCurrentUser();
        return user != null ? user.getUserId() : null;
    }
    
    /**
     * 获取当前登录用户名
     * 
     * @return 用户名
     */
    public static String getCurrentUsername() {
        UserPrincipal user = getCurrentUser();
        return user != null ? user.getUsername() : null;
    }
    
    /**
     * 获取当前登录用户角色
     * 
     * @return 用户角色
     */
    public static Integer getCurrentUserRole() {
        UserPrincipal user = getCurrentUser();
        return user != null ? user.getRole() : null;
    }
    
    /**
     * 判断当前用户是否为普通用户
     * 
     * @return 是否为普通用户
     */
    public static boolean isCurrentUserRole() {
        UserPrincipal user = getCurrentUser();
        return user != null && user.isUser();
    }
    
    /**
     * 判断当前用户是否为商家
     * 
     * @return 是否为商家
     */
    public static boolean isCurrentMerchant() {
        UserPrincipal user = getCurrentUser();
        return user != null && user.isMerchant();
    }
    
    /**
     * 判断当前用户是否为管理员
     * 
     * @return 是否为管理员
     */
    public static boolean isCurrentAdmin() {
        UserPrincipal user = getCurrentUser();
        return user != null && user.isAdmin();
    }
    
    /**
     * 检查当前用户是否已登录
     * 
     * @return 是否已登录
     */
    public static boolean isAuthenticated() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return authentication != null && authentication.isAuthenticated() 
               && authentication.getPrincipal() instanceof UserPrincipal;
    }
} 